package com.qf.web;


import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        UserService userService = new UserServiceImpl();
    //判断验证码是否正确
        //拿到输入框中的验证码
        String verifycode = req.getParameter("verifycode");
        String check_code =(String) req.getSession().getAttribute("CHECK_CODE");
        if(!check_code.equalsIgnoreCase(verifycode)){
            req.setAttribute("msg","登录失败");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

        //判断用户名和密码是否输入正确
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);
        if(user!=null){
            //登陆成功
            req.getSession().setAttribute("user",user);
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }else{
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
